package cn.gyouzhe.source.handlers;

import cn.gyouzhe.component.disruptor.AbstractHandler;
import cn.gyouzhe.entity.Good;
import cn.gyouzhe.service.IGoodService;
import cn.gyouzhe.utils.Common;
import cn.gyouzhe.source.vo.GoodVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;

/**
 * 保存数据handler
 *
 * @author wangchuan
 * @datetime 2018/2/11 23:25
 */
@Slf4j
class GoodStoreHandler extends AbstractHandler {

    @Override
    public void handle(Object data) {
        GoodVo goodVo = (GoodVo) data;

        IGoodService goodService = Common.getBean(IGoodService.class);
        String goodId = goodVo.getGoodId();
        Good good = goodService.selectGood(goodId);
        if(null == good) {
            good = Good.of(
                    goodVo.getGoodId(),
                    goodVo.getTitle(),
                    goodVo.getShortTitle(),
                    goodVo.getDesc(),
                    goodVo.getPic(),
                    goodVo.getPrice(),
                    goodVo.getCommission(),
                    goodVo.getCid(),
                    goodVo.getTmall(),
                    goodVo.getSellNum(),
                    goodVo.getSellerId(),
                    goodVo.getCouponId());
            goodService.saveGood(good);
        } else {
            String title = goodVo.getTitle();
            String shortTitle = goodVo.getShortTitle();
            String desc = goodVo.getDesc();
            BigDecimal commission = goodVo.getCommission();
            BigDecimal price = goodVo.getPrice();
            int sellNum = goodVo.getSellNum();
            boolean change = hasChange(good, title, shortTitle, desc, commission, price, sellNum);
            if(change) {
                good.setTitle(title);
                good.setShortTitle(shortTitle);
                good.setDesc(desc);
                good.setCommission(commission);
                good.setPrice(price);
                good.setSellNum(sellNum);
                goodService.updateGood(good);
            }
            goodVo.setStore(change);
        }
        goodVo.setCreateTime(good.getCreateTime());
        goodVo.setStoreGoodId(good.getId());
    }

    /**
     * 判断商品是否修改过
     * @param good   数据库商品信息
     * @param title  新标题
     * @param shortTitle  新短标题
     * @param desc  新描述
     * @param commission  新佣金比例
     * @param price   新价格
     * @param sellNum  销售数量
     * @return true表示有修改 false表示无修改
     */
    private boolean hasChange(Good good, String title, String shortTitle, String desc, BigDecimal commission, BigDecimal price, int sellNum) {
        return !(StringUtils.equals(good.getTitle(), title) &&
                StringUtils.equals(shortTitle, good.getShortTitle()) &&
                StringUtils.equals(good.getDesc(), desc) &&
                good.getCommission().compareTo(commission) != 0 &&
                good.getPrice().compareTo(price) != 0 &&
                good.getSellNum() != sellNum);
    }
}
